//============================================================================
// Name        : ad2usb.cpp
// Author      : Casey Kelso
// Copyright   : Kineticsproject.com (c) 2011
// Description : Basic ad2usb control library
//============================================================================




#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include "ad2usb.h"
#include "SerialPort.h"
#include "Parser.h"
#include "AlarmStatus.h"

void ad2usb::openPort(const char* port)
{
    serialPort->Open(port);
}

const bool ad2usb::getStatus(AlarmStatus &status)
{

 bool result = false;

if (!alarmStatusList.empty())
   {
    status = alarmStatusList.front();
    alarmStatusList.pop_front();
    result = true;
   }

   return(result);
}

const int ad2usb::getStatus(void)
{
   int result = UNKNOWN;
   
   if (!alarmStatusList.empty())
       {
       if (alarmStatusList.front().isAlarmBell())
       {
          result = SIREN;
       }
       else if (alarmStatusList.front().isAlarmTriggered())
       {
          result = TRIGGERED;
       }
       else if (AlarmStatus::STATE_ALARM_READY == alarmStatusList.front().getAlarmState())
       {
          result = READY;
       }
       else if (AlarmStatus::STATE_ALARM_AWAY == alarmStatusList.front().getAlarmState())
       {
          result = ARMED_AWAY;
       }
       else if (AlarmStatus::STATE_ALARM_STAY == alarmStatusList.front().getAlarmState())
       {
          result = ARMED_STAY;
       }

       alarmStatusList.pop_front();
   }
   return(result);
}


void ad2usb::Process(void)
{ 	
   static Parser alarmParser;
   bufferSize = serialPort->Read(buffer,BUFFER_SIZE);

   if ((serialPort->SERIAL_NO_DATA_PROCESSED != bufferSize) && (serialPort->SERIAL_ERROR != bufferSize))
   {
      alarmParser.Process(buffer,bufferSize, alarmStatusList);
   }
}



ad2usb::ad2usb() : BUFFER_SIZE(1000)
{
    serialPort = new SerialPort();
    buffer = new unsigned char[BUFFER_SIZE];

}

ad2usb::~ad2usb()
{
     serialPort->Close();
}
